package de.se.ludoapp.activity.task;

import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import de.se.ludoapp.LudoApplication;
import de.se.ludoapp.R;
import de.se.ludoapp.activity.PlayerTableActivity;
import de.se.ludoapp.gaming.Game;
import de.se.ludoapp.response.ReturncodeResponse;

/**
 * Task to send an request for a open game.
 * 
 * @author Marlen Rotert
 * 
 */
public class SendRequestTask extends AsyncTask<String, Integer, String> {

	private LudoApplication ludoApp;
	private PlayerTableActivity context;
	private boolean isSend;
	private Game gameForRequest;

	public SendRequestTask(LudoApplication ludoApp,
			PlayerTableActivity context, Game gameForRequest) {
		super();
		this.ludoApp = ludoApp;
		this.context = context;
		this.gameForRequest = gameForRequest;
	}

	/**
	 * sent request for game to server.<br>
	 * This method is executed in a concurrent thread (asynchronous). Therefore
	 * you mustn't accessed on view elements!
	 */
	@Override
	protected String doInBackground(String... params) {
		/* Execute allowUserToEnterTheGame */
		ReturncodeResponse response = ludoApp.getLudoStub().enterExistingGame(
				ludoApp.getlogedinUser().getSessionId(),
				gameForRequest.getGameId());
		if (response.getReturnCode() == 0) {
			this.isSend = true;
		}
		return response.getMsg();
	}

	/**
	 * Adapt Activity, when the request is sent. And ask for delays whether
	 * request is accepted. <br>
	 * This method is invoked when the OpenGameTask is executed. You are only
	 * allowed here to access on view Elements (TextView and Buttons)!
	 */
	@Override
	protected void onPostExecute(String result) {
		if (this.isSend == true) {
			Toast.makeText(context, "Anfrage abgesendet. Bitte warten...",
					Toast.LENGTH_LONG).show();
			// ListView and Button disable, so you can't start more games.
			Button buttonOpenNewGameTable = (Button) context
					.findViewById(R.id.buttonOpenNewGameTable);
			buttonOpenNewGameTable.setEnabled(false);
			ListView listViewOpenGames = (ListView) context
					.findViewById(R.id.listViewOpenGames);
			listViewOpenGames.setEnabled(false);
			listViewOpenGames.setBackgroundColor(Color.rgb(224, 224, 224));
			// Ask, whether request is accepted (with delay as 10 seconds)
			Handler handler = new Handler();
			handler.postDelayed(new Runnable() {
				public void run() {
					new IsRequestingPlayerAcceptedRequestTask(ludoApp, context,
							gameForRequest).execute();
				}
			}, 10000);
		}
	}
}
